package com.ruizhong.remotehelper.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MySurfaceHolder implements SurfaceHolder.Callback {

    private String aimIp = null;
    private WebSocket ws = null;
    private int screenWidth = 0;
    private int screenHeight = 0;
    private SurfaceView surfaceView=null;
    private int curBitWidth=0;
    private int curBitHeight=0;
    private int topMargin=0;

    public MySurfaceHolder(String aimIp, int screenWidth, int screenHeight, SurfaceView surfaceView) {
        this.aimIp = aimIp;
        this.screenWidth=screenWidth;
        this.screenHeight=screenHeight;
        this.surfaceView=surfaceView;
    }

    @Override
    public void surfaceCreated(@NonNull final SurfaceHolder holder) {
        String localIp = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        // return inetAddress.getAddress().toString();
                        localIp = inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("BaseScanTvDeviceClient", "获取本机IP false =" + ex.toString());
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("ws://" + aimIp + ":8080/wsServer/" + localIp)
                .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                // 连接打开时的回调
                webSocket.send("Hello, WebSocket!");
            }

            @Override
            public void onMessage(WebSocket webSocket,  ByteString bytes) {
                // 收到消息时的回调
                byte[] screenByte = bytes.toByteArray();
                Bitmap bitmap =BitmapFactory.decodeByteArray(screenByte, 0, screenByte.length);
                if (bitmap == null){
                    return;
                }
                Canvas canvas=null;
                canvas=holder.lockCanvas();
                if (canvas!=null){
                    canvas.drawBitmap(bitmap,0,0,null);
                }
                holder.unlockCanvasAndPost(canvas);
                bitmap.recycle();
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                // 连接失败时的回调
                t.printStackTrace();
            }

            // 实现其他必要的方法，如onClose, onClosing, onPing等
        };


        ws = client.newWebSocket(request, listener);

        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                float x = event.getRawX(); // 相对于屏幕的 X 坐标
                float y = event.getRawY(); // 相对于屏幕的 Y 坐标
                System.out.println("坐标：（"+x+","+y+")");
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        // 当屏幕被按下时触发
                        System.out.println("屏幕被按下");
                        try (DatagramSocket datagramSocketSend = new DatagramSocket();) {
                            InetAddress inetAddress = InetAddress.getByName(aimIp);
                            byte[] data = "echo".getBytes();
                            DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress, 11270);
//                            datagramSocketSend.setBroadcast(true);
                            datagramSocketSend.send(datagramPacket);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        UserEvent userInputEvent = new UserEvent(0,  x , y,curBitWidth,curBitHeight-topMargin);
                        ws.send(userInputEvent.toString());
                        break;

                    case MotionEvent.ACTION_UP:
                        // 当屏幕被抬起时触发
                        System.out.println("屏幕被抬起");
                        break;

                    case MotionEvent.ACTION_MOVE:
                        // 当在屏幕上移动手指时触发
                        System.out.println("屏幕移动中");
                        break;
                }

                // 返回true表示已处理此事件，不需要继续传递；返回false表示未处理此事件，需要继续传递
                return true;
            }
        });


    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        ws.close(1000, null);
    }
}
